package cn.itcast.cd.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.itcast.cd.domain.User;
import cn.itcast.cd.query.Query;
import cn.itcast.cd.resultPage.ResultPage;
import cn.itcast.cd.service.IUserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	private IUserService userService;
	private User user = new User();
	private Query query = new Query();

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public User getUser(){
		return user;
	}
	
	public Query getQuery() {
		return query;
	}

	public String input(){
		
		return INPUT;
	}
	
	public String save(){
		if(user.getId()==null){
				userService.save(user);	
		}else{
			userService.update(user);
		}
		return SUCCESS;
	}
	
	public String delete(){
		
		userService.delete(user.getId());
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json;charset=utf-8");
		try {
			//-1返回JSON是要它的格式的{key:value,key:value}
			response.getWriter().println("{\"success\":true,\"msg\":\"数据删除成功\"}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		//-2:另外这儿不能返回视图了.
		return NONE;
	}
	
	public String edit(){
		user = userService.get(user.getId());
		return INPUT;
	}
	
	public String list(){
		int currentPage = query.getCurrentPage();
		System.out.println(currentPage);
		ResultPage r = userService.queryEntity(query);
		ActionContext.getContext().put("resPage", r);
		return "list";
	}
	
}
